#include "unp.h"

void serv_echo(int fd) {
	char buf[MAXLINE];
	int n = 0;
	while((n = Read(fd, buf, MAXLINE)) > 0) {
		Write(fd, buf, n);
	}
}

void sig_child_handler(int signo) {
	int status;
	pid_t pid = 0;
	while((pid = waitpid(-1, &status, WNOHANG)) > 0) {
		printf("child process %d exit\n", pid);
	}
}

int main() {
	int fd;
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if(fd < 0) err_exit("create socket fd error");	

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(9987);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(fd,(struct sockaddr*)&addr, sizeof(addr)) != 0) err_exit("bind addr error");

	if(listen(fd, 1024) != 0) err_exit("listen error");
	Signal(SIGCHLD, &sig_child_handler);

	for(;;) {
		int client_fd = accept(fd, NULL, NULL);
		if(client_fd < 0 && errno == EINTR) continue;
		if(client_fd < 0 && errno == ECONNABORTED) {
			err_sys("accept error");
			continue;
		}
		pid_t pid = fork();
		if(pid == 0) {
			close(fd);
			serv_echo(client_fd);
			close(client_fd);
			exit(0);
		} else {
			close(client_fd);
		}
	}


	return 0;
}
